import axios, {AxiosError, type AxiosRequestConfig, type AxiosResponse} from 'axios';
import { getCsrfToken, getToken } from '@/hooks';
import {message} from 'ant-design-vue'

// 创建一个 Axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_API_URL, // 你的 API 基础 URL
  timeout: 5000, // 请求超时时间
});
axios.defaults.withCredentials = true; // 允许发送 cookie
axios.defaults.xsrfCookieName = 'csrftoken';
axios.defaults.xsrfHeaderName = 'X-CSRFToken';

// 请求拦截器
service.interceptors.request.use(
  (config: AxiosRequestConfig|any) => {
    // 在请求头中添加 token
      config.headers['Authorization'] = `Bearer ${getToken()}`;
      config.headers['X-CSRFToken'] = getCsrfToken();
    return config;
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse|any) => {
      return (response.data || {}) as HttpResponse | any;
  },
  (error: AxiosError|any) => {
      message.error(error.response?.data?.message||error.message)
      return Promise.reject({
          code:error.response?.data?.code,
          message:error.response?.data?.message
      });
  }
);

/**
 *
 */
const request = {
  get<T = any>(url: string, params?:any,config?: AxiosRequestConfig): Promise<T> {
    return service.get(url, {...config,params}).then(response => response as T);
  },
  post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return service.post(url, data, config).then(response => response as T);
  },
  put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return service.put(url, data, config).then(response => response as T);
  },
  delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return service.delete(url, config).then(response => response as T);
  },
};

export default request;